/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.felisberto.serialfwder.socket.client;

import java.util.logging.Logger;
import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.channel.ChannelStateEvent;
import org.jboss.netty.channel.ExceptionEvent;
import org.jboss.netty.channel.MessageEvent;
import org.jboss.netty.channel.SimpleChannelUpstreamHandler;

/**
 *
 * @author Filipe
 */
public class NettyClientHandler extends SimpleChannelUpstreamHandler {

    private NettyClient client;
    
    public NettyClientHandler(NettyClient client){
        this.client = client;
    }
    
    private static final Logger logger = Logger.getLogger(
            NettyClientHandler.class.getName());

    @Override
    public void messageReceived(
            ChannelHandlerContext ctx, MessageEvent e) {
        // Print out the line received from the server.
        System.err.println(e.getMessage());
        client.relayMessage((String)e.getMessage());
    }
    
    @Override
    public void channelConnected(
            ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception {
        logger.info("Connected!");
    }
    
     @Override
    public void exceptionCaught(
            ChannelHandlerContext ctx, ExceptionEvent e) {
        logger.severe(
                "Unexpected exception from downstream." +
                e.getCause());
        e.getChannel().close();
    }
}
